package top.smallway.lightbandassistant_app.UI;

import static top.smallway.lightbandassistant_app.UI.MainActivity.loginManager;
import static top.smallway.lightbandassistant_app.method.Method.gethash;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.lxj.xpopup.core.BasePopupView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.adapter.PostsAdapter;
import top.smallway.lightbandassistant_app.data.Message;
import top.smallway.lightbandassistant_app.network.Posts;

/**
 * 首页Fragment
 * 负责显示帖子列表，实现下拉刷新和上拉加载更多功能
 */
public class Home extends Fragment {
    // 是否正在加载更多数据的标记
    private boolean loadingMore = false;
    // 是否已加载完所有数据的标记
    private boolean loadingFinish = false;
    // 帖子列表的RecyclerView
    private RecyclerView recyclerView;
    // 下拉刷新控件
    private SwipeRefreshLayout srf;
    // 滚动监听器
    private RecyclerView.OnScrollListener scrollListener;
    // 布局管理器
    private LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    // 帖子列表适配器
    private PostsAdapter postsAdapter;
    // 弹出窗口视图
    private BasePopupView xPopup;
    // 帖子管理类实例
    public static Posts posts;
    // 悬浮按钮：发帖和返回顶部
    private FloatingActionButton floatingActionButton, top;
    // 帖子数据列表
    List<Message> messageList = new ArrayList<>();
    // 当前页码
    private int page;

    /**
     * 消息处理Handler
     * 处理下拉刷新、加载更多等异步操作的结果
     */
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull android.os.Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    srf.setRefreshing(false);
                    List<Message> data = (List<Message>) msg.obj;
                    postsAdapter = new PostsAdapter(data, getContext());
                    recyclerView.setAdapter(postsAdapter);
                    break;
                case 1:
                    postsAdapter.setLoadMoreEnabled(true);
                    srf.setRefreshing(false);
                    break;
                case 2:
                    List<Message> datas = (List<Message>) msg.obj;
                    if (datas.isEmpty()) {
                        recyclerView.removeOnScrollListener(scrollListener);
                    } else {
                        postsAdapter.setLoadMoreEnabled(false);
                        postsAdapter.updateData(datas);
                    }

                    break;
            }
        }
    };


    /**
     * Fragment创建时的回调
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    /**
     * 创建Fragment视图
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    /**
     * Fragment视图创建完成后的回调
     * 初始化视图组件和数据
     */
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initview(view);
        if (xPopup != null) {
            xPopup.dismiss();
        }
        srf.setRefreshing(true);
        new Thread(() -> {
            android.os.Message message = new android.os.Message();
            JSONArray jsonArray = posts.getmessages();
//            Log.d("posts.getmessage()", posts.getmessage().toString());
            for (int i = 0; i < jsonArray.size(); i++) {
                String hash;
                if (Objects.equals(jsonArray.getJSONObject(i).getString("key"), "")) {
                    hash = "";
                } else {
                    hash = "https://na.cdn.beatsaver.com/" + gethash(jsonArray.getJSONObject(i).getString("key"));
                }
                messageList.add(new Message(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("key"), jsonArray.getJSONObject(i).getString("content"), jsonArray.getJSONObject(i).getString("ip"), jsonArray.getJSONObject(i).getString("created_at"), jsonArray.getJSONObject(i).getString("author"), jsonArray.getJSONObject(i).getInteger("id"), hash));
            }
            message.obj = messageList;
            message.what = 0;
            mHandler.sendMessage(message);
        }).start();

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginManager.isLoggedIn()) {
                    startActivity(new Intent(getContext(), Create_Message.class));
                } else {
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // 设置 SwipeRefreshLayout 下拉刷新监听器
        srf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadingFinish = false;
                posts.FomatPage();
                new Thread(() -> {
                    android.os.Message message = new android.os.Message();
                    JSONArray jsonArray = posts.getmessages();
                    messageList.clear();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String hash;
                        if (Objects.equals(jsonArray.getJSONObject(i).getString("key"), "")) {
                            hash = "";
                        } else {
                            hash = "https://na.cdn.beatsaver.com/" + gethash(jsonArray.getJSONObject(i).getString("key"));
                        }
                        messageList.add(new Message(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("key"), jsonArray.getJSONObject(i).getString("content"), jsonArray.getJSONObject(i).getString("ip"), jsonArray.getJSONObject(i).getString("created_at"), jsonArray.getJSONObject(i).getString("author"), jsonArray.getJSONObject(i).getInteger("id"), hash));
                    }
                    message.obj = messageList;
                    message.what = 1;
                    mHandler.sendMessage(message);
                }).start();

            }
        });


        RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                // 判断是否满足触发加载更多的条件
                if (lastVisibleItemPosition == postsAdapter.getItemCount() - 1) {
                    // 加载更多数据
                    loadMoreData();
                }
            }
        };

        recyclerView.addOnScrollListener(scrollListener);

        top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.smoothScrollToPosition(0);
            }
        });
    }

    private void initview(View view) {
        floatingActionButton = view.findViewById(R.id.floating_action_button);
        top = view.findViewById(R.id.top);
        posts = new Posts();
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(linearLayoutManager);
        srf = view.findViewById(R.id.srf);
    }

    private void loadMoreData() {
        // 避免重复加载
        if (!loadingMore && !loadingFinish) {
            loadingMore = true; // 标记正在加载中
            srf.setRefreshing(true);
            // 模拟后台加载数据的过程，实际应根据网络请求获取数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONArray jsonArray = posts.getmessage(); // 假设这是获取数据的方法
                    if (jsonArray.isEmpty()) {
                        loadingFinish = true;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "没有帖子啦！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    // 处理数据
                    final List<Message> newMessages = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonMessage = jsonArray.getJSONObject(i);
                        String hash;
                        if (Objects.equals(jsonArray.getJSONObject(i).getString("key"), "")) {
                            hash = "";
                        } else {
                            hash = "https://na.cdn.beatsaver.com/" + gethash(jsonMessage.getString("key"));
                        }
                        newMessages.add(new Message(jsonMessage.getString("title"), jsonMessage.getString("key"), jsonMessage.getString("content"), jsonMessage.getString("ip"), jsonMessage.getString("created_at"), jsonMessage.getString("author"), jsonMessage.getInteger("id"), hash));
                    }

                    // 更新主线程的 UI
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            messageList.addAll(newMessages);
                            postsAdapter.notifyDataSetChanged();
                            loadingMore = false; // 标记加载完成
                            page++; // 更新页数
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    srf.setRefreshing(false);
                                }
                            });
                        }
                    });
                }
            }).start();
        }
    }
}